﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MAPDavy.Entities;
using MAPDavy.BusinessLogic;

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

using System.IO;

using MvcSiteMapProvider;

using System.Web.Security;

namespace MAPDavy.WebMVC3.Controllers
{
    public class AlumnosController : Controller
    {
        public AlumnosController()
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();
                container.BuildUp(this.GetType(), this);
            }
        }

        [Dependency]
        public IGradeBL GradeBL { get; set; }

        [Dependency]
        public ISeccionBL SeccionBL { get; set; }

        [Dependency]
        public IMatriculaBL MatriculaBL { get; set; }

        [Dependency]
        public IAnioLectivoBL AnioLectivoBL { get; set; }

        //
        // GET: /Alumnos/
        [Authorize(Roles = "admin,secretaria,secretariaPrimaria,secretariaSecundaria")]
        public ActionResult Index(Int32 anio=0)
        {
            var cookie = Request.Cookies["workspace"];

            if (cookie == null)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                anio = Int32.Parse(cookie.Value.ToString());
            }            
 
            var grades = GradeBL.GetAllFromGrade();

            List<Grade> lg = new List<Grade>();

            var roles = Roles.GetRolesForUser();

            if (User.IsInRole("secretariaPrimaria"))
            {
                var query = from g in grades
                            where g.Nivel == "P"
                            select g;

                lg = query.ToList();
            }

            if (User.IsInRole("secretariaSecundaria"))
            {
                var query = from g in grades
                            where g.Nivel == "S"
                            select g;

                if (lg.Count== 0)
                {                  
                    lg = query.ToList();                    
                }
                else
                {
                    lg.InsertRange(lg.Count, query.ToList());                    
                }
                            
            }

            if (User.IsInRole("admin") || User.IsInRole("secretaria"))
            {
                 lg = grades;
            }
            
            var seccions = SeccionBL.GetFromSeccionByGradeId(lg.FirstOrDefault().Id);
 
            ViewData["grade"] = new SelectList(lg, "Id", "GradeLevel");
            ViewData["seccion"] = new SelectList(seccions, "Id", "ClassName");

            var matriculas = MatriculaBL.GetFromMatriculaByCriterioAndAnioAndSeccionId("", seccions.FirstOrDefault().Id, anio);  

            return View(matriculas);
        }


        [HttpPost]
        [Authorize(Roles = "admin,secretaria,secretariaPrimaria,secretariaSecundaria")]
        public ActionResult Index(string criterio = "", Int32 grade = 0, Int32 seccion = 0)
        {
            var cookie = Request.Cookies["workspace"];

            if ( cookie == null)
            {
                 return RedirectToAction("Index", "Home");
            }

            var grades = GradeBL.GetAllFromGrade();         

            var seccions = SeccionBL.GetFromSeccionByGradeId(grade) ;

            ViewData["grade"] = new SelectList(grades, "Id", "GradeLevel");
            ViewData["seccion"] = new SelectList(seccions, "Id", "ClassName",seccion);
            
            var anio = Int32.Parse(cookie.Value.ToString());           

            var matriculas = MatriculaBL.GetFromMatriculaByCriterioAndAnioAndSeccionId(criterio, seccion, anio);

            return View(matriculas);
        }

        //
        // GET: /Alumnos/Details/5
        [Authorize(Roles = "admin,secretaria,secretariaPrimaria,secretariaSecundaria")]
        public ActionResult Details(int id)
        {
            var lista = new List<MatriculaDTO>(); 
            return View(lista);
        }

        //
        // GET: /Alumnos/Create
        [Authorize(Roles = "admin")]
        public ActionResult Create()
        {
            var cookie = Request.Cookies["workspace"];

            if (cookie == null)
            {
                return RedirectToAction("Index", "Home");
            }

            var grades = GradeBL.GetAllFromGrade();
            var seccions = SeccionBL.GetFromSeccionByGradeId(grades.FirstOrDefault().Id);

            ViewData["grade"] = new SelectList(grades, "Id", "GradeLevel");
            ViewData["SeccionId"] = new SelectList(seccions, "Id", "ClassName");

            var gender = new List<object>();

            gender.Add(new { Val = "M", Sel = "MALE" });
            gender.Add(new { Val = "F", Sel = "FEMALE" });

            ViewData["Student.Gender"] = new SelectList(gender, "Val", "Sel");
            ViewData["anio"] = cookie.Value.ToString();

            return View();
        } 

        //
        // POST: /Alumnos/Create

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult Create(FormCollection collection, HttpPostedFileBase ReportCard, HttpPostedFileBase studentPhoto)
        {
            Matricula matricula = null;
            var cookie = Request.Cookies["workspace"];
            try
            {              
               if (cookie == null)
                {
                    return RedirectToAction("Index", "Home");
                }

                Student student = new Student()
                {
                    Id = collection["StudentId"].ToString(),
                    DavyId = Int32.Parse(collection["Student.DavyId"].ToString()),
                    FirtsName = collection["Student.FirtsName"].ToString(),
                    LastName = collection["Student.LastName"].ToString(),
                    Gender = collection["Student.Gender"].ToString(),
                    BirtDate = DateTime.Parse(collection["Student.BirtDate"].ToString()),
                    FechaIngreso = DateTime.Parse(collection["Student.FechaIngreso"].ToString())
                };
                var fechaIng = collection["Student.FechaIngreso"].ToString();

                if (fechaIng != string.Empty) student.FechaIngreso = DateTime.Parse(fechaIng);

                matricula = new Matricula()
                {
                    Id = Int32.Parse(collection["Id"].ToString()),
                    StudentId = student.Id,
                    Student = student,
                    SeccionId = Int32.Parse(collection["SeccionId"].ToString()),
                    Anio = collection["Anio"].ToString(),
                    DateMatricula = DateTime.Now,
                    Activo = true
                };

                var pathR = Path.Combine(Server.MapPath("~/files/" + collection["anio"].ToString() + "/reportCard"));
                var pathP = Path.Combine(Server.MapPath("~/files/image"));

                if (!Directory.Exists(pathR))
                {
                    Directory.CreateDirectory(pathR);
                }

                if (ReportCard != null && ReportCard.ContentLength > 0)
                {
                    var fileName = "ReportCard" + Path.GetExtension(ReportCard.FileName);
                    var pathR2 = Path.Combine(pathR, fileName);
                    ReportCard.SaveAs(pathR2);

                    matricula.FileNameReportCard = "~/files/" + collection["anio"].ToString() + "/reportCard/" + fileName;
                }

                if (studentPhoto != null && studentPhoto.ContentLength > 0)
                {
                    var photoName = student.DavyId + Path.GetExtension(studentPhoto.FileName);
                    pathP = Path.Combine(pathP, photoName);
                    studentPhoto.SaveAs(pathP);

                    student.FilePhotoName = "~/files/image/" + photoName;
                }

                MatriculaBL.RegistrarMatricula(matricula);
                return RedirectToAction("Edit/" + matricula.Id);
            }
            catch (Exception ex)
            {
                var grades = GradeBL.GetAllFromGrade();
                var seccions = SeccionBL.GetFromSeccionByGradeId(grades.FirstOrDefault().Id);

                ViewData["grade"] = new SelectList(grades, "Id", "GradeLevel", seccions.Where(s => s.Id == matricula.SeccionId).SingleOrDefault().GradeId);
                ViewData["SeccionId"] = new SelectList(seccions, "Id", "ClassName", matricula.SeccionId);

                var gender = new List<object>();

                gender.Add(new { Val = "M", Sel = "MALE" });
                gender.Add(new { Val = "F", Sel = "FEMALE" });

                ViewData["Student.Gender"] = new SelectList(gender, "Val", "Sel", matricula.Student.Gender);
                ViewData["anio"] = cookie.Value.ToString();
                ViewData["message"] = ex.Message;

                return View(matricula);
            }
        }
        
        //
        // GET: /Alumnos/Edit/5
        [MvcSiteMapNode(Title = "Modificar Matricula", ParentKey = "Alumnos")]
        [Authorize(Roles = "admin,secretaria,secretariaPrimaria,secretariaSecundaria")]
        public ActionResult Edit(int id=0)
        {
            var cookie = Request.Cookies["workspace"];

            if (cookie == null)
            {
                return RedirectToAction("Index", "Home");
            }

            if (id == 0)
            {
                return RedirectToAction("Index", "Alumnos");
            }
            
            var matricula = MatriculaBL.GetFromMatriculaById(id);

            if (matricula == null)
            {
                return RedirectToAction("Index", "Alumnos");
            }

            if (cookie.Value.ToString() != matricula.Anio   )
            {
                return RedirectToAction("Index", "Alumnos");
            }

            var grades = GradeBL.GetAllFromGrade();

            var ss = (from s in SeccionBL.GetAllFromSeccion()
                      where s.Id == matricula.SeccionId
                      select s).SingleOrDefault();
            

            var seccions = SeccionBL.GetFromSeccionByGradeId(ss.GradeId);

            var gender = new List<object>();

            gender.Add(new { Val = "M", Sel = "MALE" });
            gender.Add(new { Val = "F", Sel = "FEMALE" });

            ViewData["Student.Gender"] = new SelectList(gender, "Val", "Sel", matricula.Student.Gender);
            ViewData["grade"] = new SelectList(grades, "Id", "GradeLevel",ss.GradeId);
            ViewData["SeccionId"] = new SelectList(seccions, "Id", "ClassName", matricula.SeccionId);

            return View(matricula);
        }

        //
        // POST: /Alumnos/Edit/5

        [HttpPost]
        [Authorize(Roles = "admin,secretaria,secretariaPrimaria,secretariaSecundaria")]
        public ActionResult Edit(int id, FormCollection collection, HttpPostedFileBase ReportCard, HttpPostedFileBase studentPhoto)
        {
            Matricula matricula = null;
            var cookie = Request.Cookies["workspace"];

            try
            {
                if (cookie == null)
                {
                    return RedirectToAction("Index", "Home");
                }

                Student student = new Student() 
                {
                    Id = collection["StudentId"].ToString(),
                    DavyId = Int32.Parse(collection["Student.DavyId"].ToString()),
                    FirtsName = collection["Student.FirtsName"].ToString(),
                    LastName = collection["Student.LastName"].ToString(),
                    Gender = collection["Student.Gender"].ToString(),
                    BirtDate = DateTime.Parse(collection["Student.BirtDate"].ToString()),
                    FechaIngreso = DateTime.Parse(collection["Student.FechaIngreso"].ToString())
                };
                
                var fechaIng = collection["Student.FechaIngreso"].ToString();

                if (fechaIng != string.Empty) student.FechaIngreso = DateTime.Parse(fechaIng);

                matricula = new Matricula() 
                {
                    Id= Int32.Parse(collection["Id"].ToString()),
                    StudentId = student.Id,
                    Student = student,
                    SeccionId = Int32.Parse(collection["SeccionId"].ToString()),
                };

                var activo = collection["Activo"].ToString();

                matricula.Activo = (activo == "false" ? false : true);

                var pathR = Path.Combine(Server.MapPath("~/files/" + collection["anio"].ToString() + "/reportCard"));
                var pathP = Path.Combine(Server.MapPath("~/files/image"));

                if (!Directory.Exists(pathR))
	            {
                    Directory.CreateDirectory(pathR);
	            }

                if (ReportCard != null && ReportCard.ContentLength > 0)
                {
                    var fileName = "rCard_" + student.Id + Path.GetExtension(ReportCard.FileName);
                    var pathR2 = Path.Combine(pathR, fileName);
                    ReportCard.SaveAs(pathR2);

                    matricula.FileNameReportCard = "~/files/" + collection["anio"].ToString() + "/reportCard/" + fileName;
                }

                if (studentPhoto!=null && studentPhoto.ContentLength > 0)
                {
                    var photoName = student.DavyId + Path.GetExtension(studentPhoto.FileName);
                     pathP = Path.Combine(pathP, photoName);
                    studentPhoto.SaveAs(pathP);

                    student.FilePhotoName = "~/files/image/" + photoName;
                }

                MatriculaBL.RegistrarMatricula(matricula);
                return RedirectToAction("Edit/" + matricula.Id);
            }
            catch(Exception ex) 
            {
                var grades = GradeBL.GetAllFromGrade();
                var seccions = SeccionBL.GetFromSeccionByGradeId(grades.FirstOrDefault().Id);

                ViewData["grade"] = new SelectList(grades, "Id", "GradeLevel", seccions.Where(s => s.Id == matricula.SeccionId).SingleOrDefault().GradeId);
                ViewData["SeccionId"] = new SelectList(seccions, "Id", "ClassName", matricula.SeccionId);

                var gender = new List<object>();

                gender.Add(new { Val = "M", Sel = "MALE" });
                gender.Add(new { Val = "F", Sel = "FEMALE" });

                ViewData["Student.Gender"] = new SelectList(gender, "Val", "Sel", matricula.Student.Gender);
                ViewData["anio"] = cookie.Value.ToString();
                ViewData["message"] = ex.Message;

                return View(matricula);
            }
        }

        //
        // GET: /Alumnos/Delete/5
 
        //public ActionResult Delete(int id)
        //{
        //    return View();
        //}

        //
        // POST: /Alumnos/Delete/5

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult Delete(int id)
        {
            try
            {
                MatriculaBL.DeleteMatricula(id); 

                return Json(true, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }

        [Authorize(Roles = "admin")]
        public ActionResult GetAlumnoByIdServiceJson(string q, int limit, Int64 timestamp)
        {
            var students = MatriculaBL.GetFromStudentByStudentId(q, limit); 

            var lista = from s in students
                        select new  
                        {
                            StudentId = s.Id,
                            DavyId = s.DavyId,
                            LastName = s.LastName,
                            FirtsName = s.FirtsName,
                            BirtDate = s.BirtDate.Value.ToShortDateString() ,
                            Gender = s.Gender,
                            FilePhotoName = s.FilePhotoName != null ? Url.Content(s.FilePhotoName) : s.FilePhotoName,
                            fechaIngreso = s.FechaIngreso.HasValue? s.FechaIngreso.Value.ToShortDateString():string.Empty
                        };

            return Json(lista, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult CanDeleteServiceJson(int id)
        {
            var can = MatriculaBL.CanDelete(id);

            return Json(can, JsonRequestBehavior.AllowGet);
        }
    }
}
